package com.centling.bluecollar.recruit.controller;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.annotate.JsonAnyGetter;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.loader.custom.Return;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.centling.bluecollar.base.page.PageBean;
import com.centling.bluecollar.base.page.Pagination;
import com.centling.bluecollar.customer.entity.EnterpriseCustomer;
import com.centling.bluecollar.privilege.entity.Account;
import com.centling.bluecollar.recruit.entity.DayRecruit;
import com.centling.bluecollar.recruit.service.DayRecruitService;
import com.centling.bluecollar.staff.entity.StaffInfo;
import com.centling.bluecollar.system.entity.StaffSource;
import com.centling.bluecollar.util.CommonsMethod;
import com.centling.bluecollar.util.ExportExcelsUtil;
import com.centling.bluecollar.util.StaticConstant;
import com.centling.bluecollar.staff.service.StaffInfoService;
import com.sun.org.apache.bcel.internal.generic.RETURN;
import com.sun.xml.internal.messaging.saaj.packaging.mime.internet.ContentDisposition;
/**
 * 
 * @author Administrator ��Ƹ����controller
 */
@Controller("dayRec")
@RequestMapping("/dayrec/*")
public class DayRecruitController {


	@RequestMapping("/update")
	public @ResponseBody  String update(@ModelAttribute DayRecruit dayRecruit, HttpSession session) {
		dayRecruit.setWriter("admin_super");
		dayRecruit.setDatatime(new Date());
		dayRecruitService.update(dayRecruit);
		return "";
	}
	@RequestMapping("/del")
	public @ResponseBody String delete(String ids){
		
		
		dayRecruitService.delete(ids);
		
		return "";
	}
	
	@RequestMapping("/save")
	public @ResponseBody String add(@ModelAttribute DayRecruit dayRecruit,HttpSession session){
		//没有登录所以暂时写死user
		dayRecruit.setWriter("admin_super");		
		dayRecruit.setDatatime(new Date());
		dayRecruitService.add(dayRecruit);
		return "";
	}
	/**
	 * 修改，删除，和导出选中数据时，从前台获取选中id
	 * @param id 选中id
	 * @return
	 */
	@RequestMapping("/findByid")
	public @ResponseBody String findByid(String id){
		
		return JSON.toJSONString(dayRecruitService.findByID(id));
		
	}
	/**
	 * 查询条件填写时，根据所选公司不同，动态加载企业。
	 * @param orgnizationid 公司id
	 * @param session 会话
	 * @param flag 标志位
	 * @param staff_id 职员id
	 * @return
	 */
	@RequestMapping("/findqiyeForCon")
	public @ResponseBody String findqiyeforContract(String orgnizationid ,HttpSession session,String flag,String staff_id) {
		Account account=this.getStaticAccount();
		List<EnterpriseCustomer> list=new ArrayList<EnterpriseCustomer>();
		if(StringUtils.isBlank(orgnizationid)&&(account.getPost().getId().equals(StaticConstant.HEADQUARTERS_INSURANCECLERK_ID)||account.getPost().equals(StaticConstant.BRANCH_INSURANCECONTRACTCLERK_ID))){
			if(StringUtils.isNotBlank(flag)&&"edit".equals(flag)&&StringUtils.isNotBlank(staff_id)){
				StaffInfo staff = staffInfoService.findById(staff_id);
				if(staff != null){
					List<EnterpriseCustomer> listTem=account.getEnterpriseCustomers();
					for (EnterpriseCustomer enterpriseCustomer : listTem) {
						if(enterpriseCustomer.getOrganization().getId().equals(staff.getEnterpriseCustomer().getOrganization().getId())){
							list.add(enterpriseCustomer);
						}
					}
					
				}
			}else{
			list=account.getEnterpriseCustomers();
			}
		}else if(StringUtils.isNotBlank(orgnizationid)&&(account.getPost().getId().equals(StaticConstant.HEADQUARTERS_INSURANCECLERK_ID)||account.getPost().equals(StaticConstant.BRANCH_INSURANCECONTRACTCLERK_ID))){
			List<EnterpriseCustomer> listTem=account.getEnterpriseCustomers();
			for (EnterpriseCustomer enterpriseCustomer : listTem) {
				if(orgnizationid.equals(enterpriseCustomer.getOrganization().getId())){
					list.add(enterpriseCustomer);
				}
			}
		}else {
			list=(List <EnterpriseCustomer>)dayRecruitService.findqiyeAll(orgnizationid);
		}
		if(flag!=null&&flag.equals("add")){
			List temList = new ArrayList();
			for(EnterpriseCustomer e:list)
				if((e.getStatus()+"").equals(StaticConstant.ENTERPRISECUS_END)){
					temList.add(e);
				}
			list.removeAll(temList);
		}
	
		return JSON.toJSONString(list);
	}
	/**
	 * map方法获得查询条件。
	 * @param request
	 * @param response
	 */
	@RequestMapping("/find_test")
	private void find_test(HttpServletRequest request,
			HttpServletResponse response) {
		//将登陆写死在数据中
		Account account = this.getStaticAccount();
		try {
			//获得后台的 page  row http会包含在post头中
			int currentPage = Integer.parseInt(request.getParameter("page"));		
			int pageSize    = Integer.parseInt(request.getParameter("rows"));
			//有查询条件的 序列成map来管理
			String date_start = request.getParameter("date_start")== null?"":request.getParameter("date_start");
			String date_end   = request.getParameter("date_end")== null?"":request.getParameter("date_end");
			String orgid     = request.getParameter("orgid")== null?"":request.getParameter("orgid");		
			String customerid     = request.getParameter("customer.id")== null?"":request.getParameter("customer.id");	
			Map<String, Object> searchmap = new HashMap<String, Object>();
			searchmap.put("date_start", date_start);
			searchmap.put("date_end", date_end);
			searchmap.put("orgid", orgid);
			searchmap.put("customer.id", customerid);								
			//	分页显示
			List<DayRecruit> dayRecruits = this.dayRecruitService.findByPagination(currentPage , pageSize,searchmap,account);
			int total = this.dayRecruitService.getTotal();
			response.setContentType("text/html;charset=utf-8");
			//{"total":10 , "rows":[{},{}]}
			String json = "{\"total\":"+total+" , \"rows\":"+JSON.toJSONString(dayRecruits,SerializerFeature.DisableCircularReferenceDetect)+"}";
			response.getWriter().write(json);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("/find")
	public @ResponseBody String find(@ModelAttribute PageBean page,
			@ModelAttribute DayRecruit ds,String date_start,String date_end, HttpSession session) {	
		Account  account=this.getStaticAccount();
		Pagination p = new Pagination();
		p = dayRecruitService.find(page, ds,date_start,date_end,account);
		//注意序列化。这样可以直接引用，例如  row.customer.organization.organizationName
		String json = "{\"total\":" + p.getTotal() + " , \"rows\":"
			+ JSON.toJSONString(p.getRows(),SerializerFeature.DisableCircularReferenceDetect) + "}";	
//		String json = "{\"total\":"+p.getTotal()+" , \"rows\":"+JSON.toJSONString(p.getRows())+"}";
//		System.out.print(json);
		return json;
		
	}
	/**
	 * 利用map的方法得到查询条件，集成出来。
	 * @param request
	 * @param response
	 * @return
	 */
	public Map<String, Object> getSearchMap(HttpServletRequest request,HttpServletResponse response){
			//获得后台的 page  row http会包含在post头中
			int currentPage = Integer.parseInt(request.getParameter("page"));		
			int pageSize    = Integer.parseInt(request.getParameter("rows"));
			//有查询条件的 序列成map来管理
			String date_start = request.getParameter("date_start")== null?"":request.getParameter("date_start");
			String date_end   = request.getParameter("date_end")== null?"":request.getParameter("date_end");
			String orgid     = request.getParameter("orgid")== null?"":request.getParameter("orgid");		
			String customerid     = request.getParameter("customerid")== null?"":request.getParameter("customerid");	
			Map<String, Object> searchmap = new HashMap<String, Object>();
			searchmap.put("date_start", date_start);
			searchmap.put("date_end", date_end);
			searchmap.put("orgid", orgid);
			searchmap.put("customerid", customerid);
			return searchmap;
		
	}
	@RequestMapping("/findfen")
	public @ResponseBody String findfenAll(HttpSession session){				
		Account account  = this.getStaticAccount();
		//Account account = (Account)session.getAttribute("user");		
		if(account.getPost().getId().equals(StaticConstant.HEADQUARTERS_BUSINESSCLERK_ID)||account.getPost().getId().equals(StaticConstant.OPERATION_AIRPORTSTATIONED_ID)||account.getPost().getId().equals(StaticConstant.BRANCH_AIRPORTSTATIONED_ID)){
			ArrayList orList= new ArrayList();
			orList.add(account.getOrganization());
			return JSON.toJSONString(orList);
		}else{
			return JSON.toJSONString(dayRecruitService.findfenAll(account));
		}
	}
	/***
	 * 根据公司找到对应的招聘企业
	 * @param orgnizationid 公司id
	 * @param flag 标记是增加日清 还是修改日清
	 * @return
	 */
	@RequestMapping("/findqiye")
	public @ResponseBody String findqiyeAll(String orgnizationid ,String flag){		
		Account account = this.getStaticAccount();		
		List<EnterpriseCustomer> list=new ArrayList<EnterpriseCustomer>();
		if(account.getPost().getId().equals(StaticConstant.HEADQUARTERS_BUSINESSCLERK_ID)||account.getPost().getId().equals(StaticConstant.OPERATION_AIRPORTSTATIONED_ID)||account.getPost().getId().equals(StaticConstant.BRANCH_AIRPORTSTATIONED_ID)||account.getPost().getId().equals(StaticConstant.HEADQUARTERS_INSURANCECLERK_ID)||account.getPost().equals(StaticConstant.BRANCH_INSURANCECONTRACTCLERK_ID))
			list=account.getEnterpriseCustomers();
		else if(orgnizationid==null||orgnizationid.trim().equals(""))
			list=(List <EnterpriseCustomer>)dayRecruitService.findqiyeAll(account.getOrganization().getId());
		else 
			list=(List <EnterpriseCustomer>)dayRecruitService.findqiyeAll(orgnizationid);
		if(flag!=null&&flag.equals("add")){
			List temList = new ArrayList();
			for(EnterpriseCustomer e:list)
				if((e.getStatus()+"").equals(StaticConstant.ENTERPRISECUS_END)){
					temList.add(e);
				}
			list.removeAll(temList);
		}
		return JSON.toJSONString(list);
		}
	/**
	 * 获得招聘日清的初始化界面
	 */
	@Resource
	private DayRecruitService dayRecruitService;	
	@RequestMapping("/test")
	public ModelAndView handleRequest(HttpServletRequest request,
		  HttpServletResponse response,HttpSession session) throws Exception {
		System.out.println(session.getAttribute("j_username"));	
		
		System.out.println("argarrrrrrrrrrrrrrrrrrrrraare");
		System.out.println("argarrrrrrrrrrrrrrrrrrrrraare");
		System.out.println("argarrrrrrrrrrrrrrrrrrrrraare");
		System.out.println("argarrrrrrrrrrrrrrrrrrrrraare");
		System.out.println("argarrrrrrrrrrrrrrrrrrrrraare");
		
		return new ModelAndView ("dayRec");	
	}
@Resource
public SessionFactory sessionFactory;
/**
 * 在没有加查询条件时的简单测试，结果是查询出所有数据，后来将加载页面和查询集成在一起
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
@RequestMapping("/testfind")
public @ResponseBody String testfind(HttpServletRequest request,
		  HttpServletResponse response) throws Exception {
	Session session = sessionFactory.getCurrentSession();
	session.beginTransaction();
    String hql = "from DayRecruit";  
    Query query = session.createQuery(hql);  
    List<DayRecruit> dayrecruit = query.list();  	
	session.getTransaction().commit();		
	System.out.println("----hello i am a view");
	System.out.println(JSON.toJSONString(dayrecruit));
	return JSON.toJSONString(dayrecruit);
}	
/**
 * 获得持久性登录数据数据
 * @return 一个account对象
 */
public Account getStaticAccount(){
	Session session1 = sessionFactory.getCurrentSession();							
	String hql = "from Account where loginName='admin_super'"; 
	Query query = session1.createQuery(hql);          
	Account account  =(Account)(query.list().get(0));		
	return account;
}
@Resource
private StaffInfoService staffInfoService;

/**
 * 导出勾选数据
 * @param ids 接收前台勾选的记录 ids
 * @param session 会话
 * @param response 响应
 * @return
 */
@RequestMapping(value = "/exportSelected", method = RequestMethod.POST)
public @ResponseBody String exportSelectedUser(@RequestParam String ids,  HttpSession session, HttpServletResponse response) {
    List<Object[]> dataset = dayRecruitService.exportByid(ids); 
    String[] headers = new String[]{"日期","所属公司","招聘企业","面试人数","入职人数","入职率(%)","备注"};     
    if(dataset == null || dataset.size() < 1){
        return "没有查找到相应的数据,请刷新数据后重试";
    }
    response.setContentType("application/vnd.ms-excel");//;charset=utf-8
    response.setHeader("Content-Disposition", "attachment;filename=dayRecruit.xls");
    response.setHeader("Pragma","No-cache");
    response.setHeader ( "Cache-Control", "no-store"); 
    try {
        OutputStream sos = response.getOutputStream();

        ExportExcelsUtil.exportExcel(headers, dataset, sos);//如果不需要额外数据exportExcel(headers,dataset, sos)
      //  ExportExcelsUtil.exportExcel(2,1,2,"用户信息",headers,dataset, sos);//如果不需要额外数据exportExcel(headers,dataset, sos)
        response.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "成功导出"+dataset.size()+"条用户数据。";
}
/**
 * 测试用map，将查询参数集成在map中，最后读出数据  但是查询时 起始时间是有效的。而招聘公司和企业都无效。
 * @param rec
 * @param date_start
 * @param date_end
 * @param session
 * @param response
 * @return
 */
//@RequestMapping(value = "/export", method = RequestMethod.POST)
//public @ResponseBody String export(@ModelAttribute DayRecruit rec, HttpSession session,HttpServletRequest request, HttpServletResponse response) {
//	Account  account=(Account)session.getAttribute("user");
////	Map<String, Object> searchmap = this.getSearchMap(request, response);
////	
////	int currentPage = Integer.parseInt(request.getParameter("page"));		
////	int pageSize    = Integer.parseInt(request.getParameter("rows"));
////	//有查询条件的 序列成map来管理
////	String date_start = request.getParameter("date_start")== null?"":request.getParameter("date_start");
////	String date_end   = request.getParameter("date_end")== null?"":request.getParameter("date_end");
////	String orgid     = request.getParameter("orgid")== null?"":request.getParameter("orgid");		
////	String customerid     = request.getParameter("customerid")== null?"":request.getParameter("customerid");	
////	Map<String, Object> searchmap = new HashMap<String, Object>();
////	
////	searchmap.put("date_start", date_start);
////	searchmap.put("date_end", date_end);
////	searchmap.put("orgid", orgid);
////	searchmap.put("customerid", customerid);
//	
//	List<Object[]> dataset = dayRecruitService.export(rec,account,searchmap); 
//    String[] headers = new String[]{"日期","所属公司","招聘企业","面试人数","入职人数","入职率(%)","备注"}; 
//    
//    if(dataset == null || dataset.size() < 1){
//        return "没有查找到相应的数据,请刷新数据后重试";
//    }
//    response.setContentType("application/vnd.ms-excel");//;charset=utf-8
//    response.setHeader("Content-Disposition", "attachment;filename=dayRecruit.xls");
//    response.setHeader("Pragma","No-cache");
//    response.setHeader ( "Cache-Control", "no-store"); 
//    try {
//        OutputStream sos = response.getOutputStream();
//
//        ExportExcelsUtil.exportExcel(headers, dataset, sos);//如果不需要额外数据exportExcel(headers,dataset, sos)
//      //  ExportExcelsUtil.exportExcel(2,1,2,"用户信息",headers,dataset, sos);//如果不需要额外数据exportExcel(headers,dataset, sos)
//        response.flushBuffer();
//    } catch (IOException e) {
//        e.printStackTrace();
//    }
//    return "成功导出"+dataset.size()+"条用户数据。";
//}
//导出查询的全部数据
/**
 * 导出查询数据
 * @param 获取前台的post请求。注入到对应烦的数据。字段名字要对应起来
 * @param date_start 开始时间
 * @param date_end 结束时间
 * @param session 会话
 * @param response 响应
 * @return
 */
@RequestMapping(value = "/export", method = RequestMethod.POST)
public @ResponseBody String export(@ModelAttribute DayRecruit rec, String date_start,String date_end, HttpSession session, HttpServletResponse response) {
	Account  account=this.getStaticAccount();
	List<Object[]> dataset = dayRecruitService.export(rec,date_start,date_end,account); 
    String[] headers = new String[]{"日期","所属公司","招聘企业","面试人数","入职人数","入职率(%)","备注"}; 
    
    if(dataset == null || dataset.size() < 1){
        return "没有查找到相应的数据,请刷新数据后重试";
    }
    response.setContentType("application/vnd.ms-excel");//;charset=utf-8
    response.setHeader("Content-Disposition", "attachment;filename=dayRecruit.xls");
    response.setHeader("Pragma","No-cache");
    response.setHeader ( "Cache-Control", "no-store"); 
    try {
        OutputStream sos = response.getOutputStream();

        ExportExcelsUtil.exportExcel(headers, dataset, sos);//如果不需要额外数据exportExcel(headers,dataset, sos)
      //  ExportExcelsUtil.exportExcel(2,1,2,"用户信息",headers,dataset, sos);//如果不需要额外数据exportExcel(headers,dataset, sos)
        response.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "成功导出"+dataset.size()+"条用户数据。";
}

/**
 * 批量导入储备用户数据
 * 
 * @param myFile
 * @param request
 * @param session
 * @return
 * @throws Exception
 */
@RequestMapping(value = "/imp", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public @ResponseBody String imp(@RequestParam MultipartFile myFile,
		HttpServletRequest request, HttpSession session) throws Exception {

	Account account = this.getStaticAccount();
	if (myFile == null || myFile.getSize() == 0) {
		return "未选择任何文件，请选择文件后上传！";
	}
	String fileType = myFile.getOriginalFilename().substring(
			myFile.getOriginalFilename().lastIndexOf("."));
	if (!fileType.equals(".xls") && !fileType.equals(".xlsx")) {
		return "文件格式错误，请上传.xls或.xlsx格式文件！";
	}
	//String path = CommonsMethod.getProjectPath() ;
	String path=request.getSession()
			.getServletContext().getRealPath("/")
			+ "/importReserveExcel/";
	String fileattr = CommonsMethod.getNowCorrect2Millisecond()
			+ myFile.getOriginalFilename().substring(
					myFile.getOriginalFilename().lastIndexOf("."));
	final File targetFile = new File(path, fileattr);
	if (!targetFile.exists()) {
		targetFile.mkdirs();
	}
	try {
		myFile.transferTo(targetFile);
	} catch (IllegalStateException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	ArrayList<Object> dataList = new ArrayList<Object>();
	try {
		dataList = dayRecruitService.readExcel(
				targetFile.getAbsolutePath(), 4);
	} catch (Exception e) {
		return e.getMessage();
	}
	try {
		String failImport = dayRecruitService.importDayrecruit(
				dataList, account);
	} catch (RuntimeException e) {
		return e.getMessage();
	} catch (Exception e) {
		return "请仔细核对上传格式（参考备注）";
	}
	return "上传成功";
}

private static final String[] headers = new String[] {"日清日期","备注","面试人数","入职人数","招聘企业"};

}





